package org.middleware.service.system;

import org.middleware.common.BusinessException;
import org.middleware.dao.system.SysEnterprisesDao;
import org.middleware.entity.system.SysEnterprises;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author zhiqiangwu
* @description 针对表【sys_enterprises(企业表)】的数据库操作Service
* @createDate 2025-09-05 16:40:01
*/
@Service
public class SysEnterprisesService {

    @Autowired
    private SysEnterprisesDao enterprisesDao;

    public List<SysEnterprises> getEnterprises() {
        List<SysEnterprises> enterprises = enterprisesDao.getEnterprises();
        return enterprises;
    }

    public SysEnterprises getEnterpriseByID(int id){
        SysEnterprises enterprises = enterprisesDao.getEnterpriseByID(id);
        if (enterprises == null) {
            throw new BusinessException("企业不存在");
        }
        return enterprises;
    }

    public int createEnterprise(SysEnterprises enterprises) {
        if (enterprises.getCode() == null || "".equals(enterprises.getCode().trim())) {
            throw new BusinessException("企业编号不能为空");
        }
        if (enterprises.getName() == null || "".equals(enterprises.getName().trim())) {
            throw new BusinessException("企业名称不能为空");
        }
        SysEnterprises exist = enterprisesDao.getEnterprisesByCode(enterprises.getCode());
        if (exist != null) {
            throw new BusinessException("企业已存在");
        }
        int result = enterprisesDao.createEnterprise(enterprises);
        if (result == 0) {
            throw new BusinessException("企业创建失败");
        }
        return result;
    }

    public int updateEnterprise(SysEnterprises enterprises) {
        if (enterprises == null || enterprises.getId() == null || enterprises.getId() < 0) {
            throw new BusinessException("企业信息参数错误");
        }
        return enterprisesDao.update(enterprises);
    }

    public List<SysEnterprises> getEnterprisesOfCurrentUser(int id, int isAdmin) {
        List<SysEnterprises> result;
        if (isAdmin == 1) {
            result = enterprisesDao.getEnterprises();
        } else {
            result = enterprisesDao.getEnterprisesOfCurrentUser(id);
        }
        return result;
    }

}
